﻿using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Http;
using GGGK.Tea.Api.Models;
using TiTi.tea.Api.Models;
using TiTi.tea.Comm;

namespace TiTi.tea.Api.Controllers
{
    public class PaysController : ApiController
    {
        [HttpPost]
        public Result Post(PayParams p)
        {
            //https://www.xunhupay.com/doc/api/pay.html
            var json = new JObject();
            p.orderId = p.orderId.IsNullOrEmpty() ?Tools.GetSnowFlakeId().ToString() : p.orderId;

            try
            {
                var dic = new Dictionary<string, string>
                    {
                        {"version", "1.1"},
                        {"lang", "zh-cn"},
                        {"plugins", "test-001"},
                        {"appid", Config.HPJAppID},//appid
	                    {"appsecret",Config.HPJAppSecret},//appsecret
	                    {"trade_order_id", p.orderId},//订单号
	                    {"payment",p.paymentType},//支付类型
	                    {"total_fee", p.money},//金额
	                    {"title", p.title},//标题，只能数字或英文（中文乱码，找不到原因）
	                    {"time", Tools.GetSnowFlakeId().ToString()},//时间戳
	                    {"notify_url", p.notify_url},//通知链接
	                    {"return_url", p.return_url},//跳转链接
	                    {"nonce_str", Tools.GetRandCode(32)},//随机字符串
	                };

                dic.Add("hash", Sign(dic));

                var sr = JsonConvert.DeserializeObject<SamplesResult>(PostHttp(dic));

                json.Add(new JProperty("openid", sr.Openid));
                json.Add(new JProperty("url", sr.Url));
                json.Add(new JProperty("errcode", sr.Errcode));
                json.Add(new JProperty("errmsg", sr.Errmsg));
                json.Add(new JProperty("hash", sr.Hash));

                //var result = HttpGet(sr.Url);//解析出来样式会有问题
                //json.Add(new JProperty("html", result));
            }
            catch (Exception ex)
            {

                throw ex;
            }

            return new Result() { code = 1, msg = "OK", data = json };// (json.ToString());
        }

        private static string Sign(Dictionary<string, string> dicArray)
        {
            var prestr = new StringBuilder();
            foreach (var temp in dicArray.OrderBy(o => o.Key))
            {
                prestr.Append(temp.Key + "=" + temp.Value + "&");
            }
            var nLen = prestr.Length;
            prestr.Remove(nLen - 1, 1);
            var signValue = Tools.Md5(prestr + Config.HPJAppSecret);
            return signValue;
        }

        private static string PostHttp(Dictionary<string, string> dicArray)
        {
            string result;
            try
            {
                var req = (HttpWebRequest)WebRequest.Create("https://api.xunhupay.com/payment/do.html");
                req.KeepAlive = false;
                req.Method = "POST";
                req.ContentType = "application/x-www-form-urlencoded";
                req.Accept = "application/json";

                var paramData = ParamData(dicArray);
                var data = Encoding.Default.GetBytes(paramData);

                req.ContentLength = data.Length;

                var swrite = req.GetRequestStream();
                swrite.Write(data, 0, data.Length);
                swrite.Close();

                var resp = (HttpWebResponse)req.GetResponse();
                var stream = resp.GetResponseStream();

                //获取响应内容
                var reader = new StreamReader(stream ?? throw new InvalidOperationException(), Encoding.UTF8);
                result = reader.ReadToEnd();
            }
            catch (WebException ex)
            {
                result = ex.Message;
            }

            return result;
        }

        private static string ParamData(Dictionary<string, string> dicArray)
        {
            var prestr = new StringBuilder();
            foreach (var temp in dicArray)
            {
                prestr.Append(temp.Key + "=" + temp.Value + "&");
            }

            var nLen = prestr.Length;
            prestr.Remove(nLen - 1, 1);

            return prestr.ToString();
        }

        public static string HttpGet(string url)
        {
            string result = "";
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "Get";
            //req.Headers.Add()
            try
            {
                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                Stream stream = resp.GetResponseStream();
                //获取内容
                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                {
                    result = reader.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                result = ex.Message;
            }
            return result;
        }
    }
}
